<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar
      title="注册 / 登录"
      left-arrow
      @click-left="$router.back()"
      class="app-nav-bar"
    />
    <!-- 登录表单 -->
    <van-form
      ref="login-form"
      @submit="onLogin"
      :show-error="false"
      :show-error-message="false"
      @failed="onFailed"
      validate-first
    >
      <van-field
        name="mobile"
        v-model="user.mobile"
        icon-prefix="toutiao"
        left-icon="shouji"
        placeholder="请输入手机号"
        :rules="formRules.mobile"
      />
      <van-field
        v-model="user.code"
        clearable
        icon-prefix="toutiao"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        :rules="formRules.code"
      >
        <template #button>
          <van-count-down
            :time="1000 * 60"
            format="ss s"
            v-if="isCountDownShow"
            @finish="isCountDownShow = false"
          />
          <van-button
            :loading="isSendSmsLoading"
            class="send-btn"
            size="small"
            round
            @click.prevent="onSendMs"
            v-else
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <!-- 登录 -->
      <div class="login-btn-wrap">
        <van-button class="login-btn" type="info" block>登录</van-button>
      </div>
    </van-form>

    <h3>请使用：手机号 13911111111 验证码 246810</h3>
  </div>
</template>

<script>
import { login, sendSms } from "@/api/user";
export default {
  name: "LoginIndex",
  data() {
    return {
      user: {
        mobile: "", // 手机号
        code: "", // 验证码
      },
      // 表单验证规则
      formRules: {
        // 手机号的验证规则
        mobile: [
          { required: true, message: "请输入手机号" },
          { pattern: /^\d{11}$/, message: "手机号格式错误" },
        ],
        // 验证码的验证规则
        code: [
          { required: true, message: "请输入验证码" },
          { pattern: /^\d{6}$/, message: "验证码格式错误" },
        ],
      },
      isCountDownShow: false, // 是否展示倒计时
      isSendSmsLoading: false, // 是否展示发送验证码按钮的loading
    };
  },
  methods: {
    // 表单校验失败的回调
    onFailed(err) {
      if (err.errors[0]) {
        this.$toast({
          message: err.errors[0].message,
          position: "top",
        });
      }
    },
    // 点击发送验证码
    async onSendMs() {
      try {
        // 验证手机号
        await this.$refs["login-form"]
          .validate("mobile")
          .catch(({ message }) => {
            this.$toast({
              message,
              position: "top",
            });
            return Promise.reject();
          });
        // 发送验证码按钮展示loading效果，防止用户网速慢时频繁点击，拿到服务器结果后置为false
        this.isSendSmsLoading = true;

        // 发送请求
        await sendSms(this.user.mobile).catch((err) => {
          this.isSendSmsLoading = false;
          this.$toast({
            message: "发送太频繁了，请稍后重试",
            position: "top",
          });
        });
        this.isSendSmsLoading = false;
        this.isCountDownShow = true;
      } catch (err) {}
    },
    // 登录
    async onLogin() {
      // 提示文本
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      try {
        const res = await login(this.user);
        this.$store.dispatch("setUser", res.data.data);
        this.$toast.success("登录成功");

        this.$store.commit("REMOVECACHEPAGE", "LayOutIndex");

        this.$router.push(this.$route.query.redirect || "/home");
      } catch (err) {
        this.$toast.fail("登录失败，手机号或验证码错误");
      }
    },
  },
};
</script>

<style scoped lang="less">
.login-container {
  .send-btn {
    padding: 0;
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 3px;
      color: #666666;
    }
  }

  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      border-radius: 6px;
      background-color: #6db4fb;
      border: none;
      .van-button__text {
        font-size: 15px;
      }
    }
  }

  h3 {
    font-weight: 400;
    font-size: 12px;
    text-align: center;
    color: rgba(0, 0, 0, 0.4);
  }

  /deep/.van-field__button {
    display: flex;
    align-items: center;
  }
}
</style>
